#!/usr/bin/zsh

export MIRACAST_PID_FILE=/var/run/MiracastTester.pid
export MIRACAST_LISTENER=/usr/local/bin/MiracastTester
export MIRACAST_LISTENER_SHORT=MiracastTester
export MIRACAST_PLAYER=/app/client/miracast_player

runpid()
{
    PIDFILE=$1
    shift

    PROG=$1
    shift

    $PROG $* &

    PID=$!
    echo $PID > $PIDFILE

    wait $PID
    RESULT=$?

    rm $PIDFILE

    return $RESULT
}

cleanup()
{
    echo "Cleanup: stopping miracast service"

    if [ -f $MIRACAST_PID_FILE ] ; then
        echo "Cleanup: killing Miracast listener"
        /bin/pkillwait -x $MIRACAST_LISTENER_SHORT
        rm -f $MIRACAST_PID_FILE

        # Miracast listener is running, this means we are the ones
        # that turned on the radio. Turn it off here.
        echo "Cleanup: turning off radio"
        wl radio off
    fi
    rm -f /tmp/miracast-listener
    exit 128
}

runlistener()
{
    RECEIVER_NAME="GFiberTV"
    if [ -e /config/nickname ]; then
        RECEIVER_NAME=`cat /config/nickname`
    fi
    runpid $MIRACAST_PID_FILE $MIRACAST_LISTENER $MIRACAST_PLAYER "$RECEIVER_NAME"
    rm -f /tmp/miracast-listener
    echo "Listener exited: turning off radio"
    wl radio off
}

trap "cleanup" HUP INT TERM

export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"
export NETAPP_DEBUG=y

watch-dir /tmp | while read LINE ; do
    if [ "miracast-listener" = "$LINE" ] ; then
        if [ -f /tmp/miracast-listener ] ; then
            echo "Request to start miracast listener"
            if [ -f $MIRACAST_PID_FILE ] ; then
                echo "Listener already running"
            else
                export ORIGINAL_RADIO=`wl radio`
                if [ "0x0000" = "$ORIGINAL_RADIO" ] ; then
                    echo "ERROR: WiFi radio is currently ON. Please turn it OFF to run Miracast"
                else
                    echo "Turning on radio"
                    wl radio on
                    echo "Launching listener"
                    runlistener &
                fi
            fi
        else
            echo "Request to stop miracast listener"
            if [ -f $MIRACAST_PID_FILE ] ; then
                kill `cat $MIRACAST_PID_FILE`
            else
                echo "Listener is not running"
            fi
        fi
    fi
done
